package com.yanqu.road.queue;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;
import java.util.concurrent.ExecutorService;

public class AutoDriveQueue<MsgType extends Runnable> {
    private final static Logger logger = LogManager.getLogger(AutoDriveQueue.class.getName());

    //队列
    private Queue<MsgType> msgQueue;

    //状态
    private boolean isRunning = false;

    //线程池
    private ExecutorService executorService;


    public void remove() {
        synchronized (msgQueue) {
            try {
                isRunning = false;

                // 如果队列内还有消息 调用remove移除最早的消息
                if (msgQueue.size() > 0) {
                    msgQueue.remove();
                }
                if (msgQueue.size() != 0) {
                    if (!executorService.isShutdown()) {
                        executorService.execute(msgQueue.peek());
                        isRunning = true;
                    }
                }
            } catch (Exception e) {
                logger.error("remove MsgQueue exception:", e);
            }
        }
    }


    /**
     * 清空所有消息
     */
    public void clear() {
        synchronized (msgQueue) {
            msgQueue.clear();
        }
    }

    public AutoDriveQueue(ExecutorService executorService) {
        this.executorService = executorService;
        this.msgQueue = new LinkedList<MsgType>();
    }


    public void add(MsgType msg) {
        synchronized (msgQueue) {
            msgQueue.add(msg);
            if (msgQueue.size() != 0 && !isRunning) {
                if (!executorService.isShutdown()) {
                    executorService.execute(msg);
                    isRunning = true;
                }
            }
        }
    }


    public void execute(MsgType type) {
        executorService.execute(type);
    }


}
